package com.link_with_health.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link_with_health.config.YmlProperties;
import com.link_with_health.service.BaseService;
import com.link_with_health.service.SmsService;
import com.link_with_health.utils.HttpConnUtil;
import com.sun.javafx.collections.MappingChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.TreeMap;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

@Service("thirdPartySmsSender")
public class TencentCloudSmsServiceImp extends BaseService implements SmsService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    YmlProperties ymlProperties;
    @Resource
    HttpConnUtil httpConnUtil;

    private final static String CHARSET = "UTF-8";
    private String smsUrl;
    private String appId;
    private String version;
    private String sign;
    private String auth;
    private String userId;
    private String key;
    private String action;

    @PostConstruct
    private void init(){
        smsUrl = ymlProperties.getSmsCfg().get("host");
        sign = ymlProperties.getSmsCfg().get("SignName");
        key = ymlProperties.getSmsCfg().get("SecretKey");
        userId = ymlProperties.getSmsCfg().get("SecretId");
        appId = ymlProperties.getSmsCfg().get("SDKAppID");
        version = ymlProperties.getSmsCfg().get("Version");
        auth = ymlProperties.getSmsCfg().get("Authorization");
    }
    /**
     * 发送短信
     * @param phone 手机号
     * @param msg 短信信息 格式 模板编号-变量-变量
     * @return
     */
    @Override
    public Boolean send(String phone, String msg){
        TreeMap<String, Object> params = new TreeMap<String, Object>();
        Long timestamp = System.currentTimeMillis();
        Integer timestampInt = Math.toIntExact(timestamp);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String utcTime = format.format(new Date(timestamp));
        String authStr = "";
        params.put("SDKAppID","1400653014");
        params.put("TemplateId","");
        params.put("TemplateParamSet","");


        try{
            httpConnUtil.setHeader("X-TC-Action","SendSms");
            httpConnUtil.setHeader("X-TC-Timestamp", timestampInt.toString());
            httpConnUtil.setHeader("X-TC-Version","2021-01-11");
            httpConnUtil.setHeader("Authorization","");
            String result =  httpConnUtil.httpPost("","","");
            if(isSendSucessfuly(result)){
                return true;
            }
        }catch (Exception e){
            logger.error("",e);
        }

        return false;
    }

    private String sign(String s, String key, String method) throws Exception {
        Mac mac = Mac.getInstance(method);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(s.getBytes(CHARSET));
        return DatatypeConverter.printBase64Binary(hash);
    }

    private Boolean isSendSucessfuly(String response){
        JSONObject respJson = JSONObject.parseObject(response).getJSONObject("Response");
        JSONArray respArray = respJson.getJSONArray("SendStatusSet");
        if("Ok".equals(respJson.getString("Code")))
            return true;

        logger.error(respJson.getString("Error"));
        return false;
    }

}
